<template>
  <div class="user-content">

    <div class="tree-wrapper">
      <el-tree
        :data="deptTree.treeData"
        :props="deptTree.defaultProps"
        :default-expand-all=true
        :highlight-current=true
        :expand-on-click-node=false
        node-key="id"
        ref="deptTree"
        @node-click="nodeClick">
      </el-tree>
    </div>

    <div class="main-wrapper">
      <!-- 搜索 -->
      <el-form :inline="true" class="query-box">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="queryForm.email" placeholder="邮箱" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择" clearable class="query-select">
            <el-option v-for="(item, index) in status" :key="index" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form>
      <div class="option-box">
        <el-button type="primary" v-has="'user:add'" @click="addUser">添加用户</el-button>
      </div>

      <el-table :data="tableData" stripe style="width: 100%" ref="multipleTable"
        v-loading="tableLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading">
        <el-table-column type="selection" />
        <el-table-column prop="username" label="用户名" sortable />
        <el-table-column prop="deptName" label="部门"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="gender" label="性别">
          <template slot-scope="scope">
            {{transformDict('gender', scope.row.gender)}}
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="生日" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{transformDict('status',scope.row.status)}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" v-has="'user:update'" @click="editUser(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" v-has="'user:setRole'" @click="setRole(scope.$index, scope.row)">设置角色</el-button>
            <el-button type="text" class="text-button-del" v-has="'user:delete'"  @click="delUser(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @current-change="pageChange" layout="prev, pager, next"
          :current-page="queryForm.pageNum" :page-size="queryForm.pageSize" :total="totalNum">
        </el-pagination>
      </div>
    </div>

    <!--dialog弹窗-->
    <el-dialog :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="680px"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="userForm" :model="userForm" :inline="true" :rules="userFormRules" label-position="right" label-width="80px">
        <el-input type="hidden" v-model="userForm.id"/>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item v-if="!this.isEdit" label="密码" prop="password">
          <el-input type="password" v-model="userForm.password" placeholder="请输入密码" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userForm.gender" placeholder="请选择性别" class="handle-select">
            <el-option v-for="(g, index) in gender" :key="index" :label="g.name" :value="g.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptName">
          <el-input v-model="userForm.deptName" placeholder="请选择部门"  class="handle-icon">
            <el-button @click="openInnerDialog" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" class="handle-input"></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker align="right" v-model="userForm.birthday" placeholder="请选择生日" class="handle-date" ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="userForm.remark" placeholder="请输入备注" class="handle-textarea"></el-input>
        </el-form-item>
      </el-form>

      <!--内层弹框-->
      <el-dialog
        title="选择部门"
        :visible.sync="innerVisible"
        width="20%"
        append-to-body>
        <el-tree
          :data="deptTree.treeData"
          :props="deptTree.defaultProps"
          :default-expand-all=true
          :highlight-current=true
          :expand-on-click-node=false
          node-key="id"
          ref="subTree">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="selectDept">确 定</el-button>
        </span>
      </el-dialog>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading"  @click="userFormSubmit">提 交</el-button>
      </span>
    </el-dialog>

    <!--设置角色-->
    <el-dialog title="设置角色"
      :visible.sync="role.dialogVisible"
      width="30%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-checkbox-group v-model="role.form.roleIds">
        <el-checkbox v-for="(r, index) in role.roles" :label="r.id" :key="index">{{r.roleName}}</el-checkbox>
      </el-checkbox-group>

      <span slot="footer" class="dialog-footer">
        <el-button @click="role.dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="role.loading"  @click="setRoleFormSubmit">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as user from '@/api/user'
import {calcMd5} from '@/utils/tool'
import {treeData as deptTreeData} from '@/api/dept'
import {mapGetters} from 'vuex'

export default {
  name: 'UserList',
  data () {
    return {
      deptTree: {
        defaultProps: {
          children: 'children',
          label: 'deptName'
        },
        treeData: []
      },
      queryForm: {
        username: '',
        status: '',
        email: '',
        deptId: '',
        deptName: '',
        pageNum: this.GLOBAL.pageNum,
        pageSize: this.GLOBAL.pageSize
      },
      userForm: {
        id: '',
        username: '',
        password: '',
        gender: '',
        birthday: '',
        email: '',
        phone: '',
        remark: '',
        deptName: '',
        deptId: ''
      },
      role: {
        dialogVisible: false,
        loading: false,
        roles: [],
        form: {
          userId: '',
          roleIds: []
        }
      },
      dialogVisible: false, // 弹窗
      dialogTitle: '', // 弹窗标题
      isEdit: false, // 是否为修改操作
      innerVisible: false,
      totalNum: 1, // 总页数
      tableData: [], // 表格数据
      tableLoading: true,
      loading: false,

      userFormRules: {
        username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '密码长度为6~20位', trigger: 'blur'}
        ],
        gender: [{required: true, message: '性别不能为空', trigger: 'blur'}],
        deptName: [{required: true, message: '部门不能为空', trigger: 'blur'}],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {type: 'email', message: '邮箱格式错误', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {message: '手机号格式错误', pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    pageChange (val) {
      this.queryForm.pageNum = val;
      this.queryList();
    },
    transformDict (key, code) {
      return this.dictinfo(this.GLOBAL.dictKey[key], code);
    },
    search () {
      // this.pageNum = this.GLOBAL.pageNum;
      this.queryList();
    },
    queryList () {
      let param = this.GLOBAL.handlerQueryParam({
        ...this.queryForm
      });
      user.userList(param).then(res => {
        this.tableData = res.data.list;
        this.totalNum = Number(res.data.total);
        this.tableLoading = false;
      });
    },
    getDeptTreeData () {
      deptTreeData().then(res => {
        this.deptTree.treeData = [...res.data];
      });
    },
    nodeClick (value, node, self) {
      this.queryForm.deptId = value.id;
      this.queryList();
    },
    openInnerDialog () {
      this.innerVisible = true;
    },
    selectDept () {
      let curNode = this.$refs.subTree.getCurrentNode();
      console.log(curNode);
      if (curNode) {
        if (curNode.children.length > 0) {
          this.$message({
            message: '不能选择父节点(' + curNode.deptName + ')',
            type: 'error'
          });
        } else {
          this.userForm.deptId = curNode.id;
          this.userForm.deptName = curNode.deptName;
          this.innerVisible = false;
        }
      }
    },
    addUser () {
      this.isEdit = false;
      this.dialogTitle = '添加用户';
      this.GLOBAL.clearObject(this.userForm);
      this.dialogVisible = true;
    },
    editUser (index, row) {
      this.isEdit = true;
      this.dialogTitle = '编辑用户';
      this.GLOBAL.clearObject(this.userForm);
      user.getUserById(row.id).then(res => {
        this.userForm = {...res.data};
        this.userForm.deptId = row.deptId;
        this.userForm.deptName = row.deptName;
        this.dialogVisible = true;
      });
    },
    delUser (index, row) {
      this.$confirm('确认删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          user.delUser(row.id)
            .then(res => {
              this.$message.success('删除成功');
              this.queryList();
            });
        })
    },
    userFormSubmit () {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let param = this.GLOBAL.handlerQueryParam({
            ...this.userForm
          });
          console.log(param.password, 'before')
          if (param.password) {
            param.password = calcMd5(param.password);
          }
          console.log(param.password)
          if (this.isEdit) {
            user.editUser(param)
              .then(res => {
                this.loading = false;
                this.dialogVisible = false;
                this.queryList();
              })
              .catch(() => {
                this.loading = false;
              })
          } else {
            user.addUser(param)
              .then(res => {
                this.loading = false;
                this.dialogVisible = false;
                this.queryList();
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    setRole (index, row) {
      user.findUserRole(row.id).then(res => {
        this.role.roles = [...res.data.roles];
        this.role.form.roleIds = [...res.data.selected];
        this.role.form.userId = row.id;
        this.role.dialogVisible = true;
      });
    },
    setRoleFormSubmit () {
      this.role.loading = true;
      user.setRole(this.role.form).then(res => {
        this.role.loading = false;
        this.role.dialogVisible = false;
      }).catch(() => {
        this.role.loading = false;
      });
    }
  },
  created () {
    this.queryList();
    this.getDeptTreeData();
  },
  computed: {
    ...mapGetters(['dictinfo', 'dictList']),
    status () {
      return this.dictList(this.GLOBAL.dictKey.status);
    },
    gender () {
      return this.dictList(this.GLOBAL.dictKey.gender);
    }
  },
  watch: {
    dialogVisible (val, oldValue) {
      if (val && this.$refs.userForm !== undefined) {
        this.$refs.userForm.resetFields();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$left: 200px;
.user-content {
  display: flex;

  .tree-wrapper {
    width: 15%;
    min-height: 400px;
    border-right: 2px solid #f0f0f0;
  }

  .main-wrapper {
    width: 83%;
    padding-left: 15px;
    padding-top: 15px;

    .option-box {
      margin-bottom: 10px;
    }
  }
}
</style>
